package com.kgc.sbt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.kgc.sbt.api.BuyVip;
import com.kgc.sbt.beans.QueryCoupons;
import com.kgc.sbt.beans.UserCoupons;
import com.kgc.sbt.beans.Vip;
import com.kgc.sbt.constant.WxpayConstant;
import com.kgc.sbt.service.BuyVipService;
import com.kgc.sbt.service.OrderService;
import com.kgc.sbt.utils.RequestResult;
import com.kgc.sbt.utils.ResultBuildUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created on 2021/8/10.
 * <p>
 * Author: songhe
 * <p>
 * Description:微信支付操作入口
 */
@RestController
@Slf4j
@Api(tags = "5 购买会员操作入口")
@RequestMapping("/wechatPay")
public class BuyVipController extends BaseController{

    @Autowired
    private OrderService orderService;

    @Autowired
    private BuyVipService buyVipService;

    @Reference(timeout = 30000)
    private BuyVip buyVip;


    int uId=0;

    /**
     * @author : songhe
     * @date : 2021/8/10
     * @return :
     * @description :  请求微信官方统一下单(返回支付链接 ， 拿到链接才可以扫码支付)
     */
    @ApiOperation(value = "购买会员")
    @GetMapping("/unifiedrder")
    public RequestResult<Map<String,String>> wechatPayUnifiedOrder(HttpServletRequest request) throws Exception {

        // 获取用户标识的token
        String token = request.getHeader("token");

        if(token == null){
            log.error("------ 用户标识token为空 ------");
            return ResultBuildUtil.fail("token_error_null", "用户标识token为空");
        }

        // 根据token获取用户id
        Integer userId = orderService.selectIdByToken(token);
        // 判断用户id是否合法
        if(userId == 0){
            log.error("------ token非法，无法识别用户 ------");
            return ResultBuildUtil.fail("token_error_illegal", "用户标识token非法");
        }

        // 封装微信统一下单参数（xml格式）
        String wxpayOrderXml = buyVipService.getWxpayOrderParamsXml(this.getRemoteIp(request));

        log.info("------ 1 请求微信官方统一下单参数：{}    ------", wxpayOrderXml);
        Map<String, String> wxpayOrderReturnMap = buyVipService.sendToWxpayUnifiedOrder(wxpayOrderXml);

        log.info("------ 2 请求微信官方统一下单返回结果：{} ------",wxpayOrderReturnMap);
        // 返回数据集合
        Map<String, String> wxpayOrderData = new HashMap<>();

        // 结果解析和返回
        if (WxpayConstant.WXPAY_RETURN_CODE_SUCCESS.equals(wxpayOrderReturnMap.get("return_code"))
                && WxpayConstant.WXPAY_RETURN_CODE_SUCCESS.equals(wxpayOrderReturnMap.get("result_code"))) {

            // 交易类型
            wxpayOrderData.put("trade_type", wxpayOrderReturnMap.get("trade_type"));

            // 预交易会话标识
            wxpayOrderData.put("prepay_id", wxpayOrderReturnMap.get("prepay_id"));

            // 二维码
            wxpayOrderData.put("code_url", wxpayOrderReturnMap.get("code_url"));

            uId=userId;

            return ResultBuildUtil.success(wxpayOrderData);

        }

        // 返回微信下单接口错误结果
        return ResultBuildUtil.fail();
    }


    /**
     * @author : songhe
     * @date : 2021/8/11
     * @return : 
     * @description :  接收微信支付结果异步通知
     */
    @ApiOperation(value = "接收微信支付结果异步通知")
    @ApiIgnore
    @RequestMapping(value="/resultNotify", method = RequestMethod.POST)
    public void wechatPayResultNotify(HttpServletRequest request , HttpServletResponse response) {

        //解析回调结果，同步响应微信官方xml内容
        String resultNotifyResponseXml = "";

        log.info("支付成功userId： {}",uId);
        buyVip.getVip(uId);

        //解析微信结果回调,微信会吧相关支付结果及用户信息通过数据流的形式发送给用户
        try (InputStream inputStream = request.getInputStream()){

            //高效读取流数据
            BufferedReader bfr = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

            //定义变量接收每次读取的内容
            String readLine = "";
            //保存所有的回调内容
            StringBuilder resultNotifyStr = new StringBuilder();
            while ((readLine =bfr.readLine())!= null){
                resultNotifyStr.append(readLine);
            }

            log.info("------ 3 微信异步通知支付结果：{} ------",resultNotifyStr.toString());



            //解析获取结果
            resultNotifyResponseXml = buyVipService.resolveWxpayResultNotify(resultNotifyStr.toString());

            //同步给微信官方响应结果
            PrintWriter out = response.getWriter();
            out.write(resultNotifyResponseXml);
            out.flush();
            out.close();
            log.info("------ 4 微信响应微信官方结果：{}",resultNotifyResponseXml);

        }catch (Exception e){
            log.info("微信回调解析流数据异常：{}",e.getMessage());
        }

    }

    /**
     * @author : songhe
     * @date : 2021/8/18
     * @return :
     * @description :  查看是否是会员及到期时间
     */
    @ApiOperation(value = "查看是否是会员及到期时间")
    @GetMapping("/queryTimeByUserId")
    public RequestResult<Vip> queryTimeByUserId(HttpServletRequest request){
        // 获取用户标识的token
        String token = request.getHeader("token");

        if(token == null){
            log.error("------ 用户标识token为空 ------");
            return ResultBuildUtil.fail("token_error_null", "用户标识token为空");
        }

        // 根据token获取用户id
        Integer userId = orderService.selectIdByToken(token);
        // 判断用户id是否合法
        if(userId == 0){
            log.error("------ token非法，无法识别用户 ------");
            return ResultBuildUtil.fail("token_error_illegal", "用户标识token非法");
        }




        return ResultBuildUtil.success(buyVip.queryDaysBuyUserId(userId));
    }

}
